﻿$(function () {
    $.kish.EditCarStore = {};
    $.extend($.kish.EditCarStore, {
        WithTotal: null,
        carStoreID: null,
        initializing: function () {
            $.kish.EditCarStore.SetProvDrp();
            $.kish.EditCarStore.carStoreID = $.Jahanutility.getParameterByName("ID");
            if ($.kish.EditCarStore.carStoreID != "0" && $.kish.EditCarStore.carStoreID != '') {
                $.kish.EditCarStore.GetCarStoreInfo();
                $.kish.EditCarStore.ListCarInCarStore(0, 20, true);
            };
            $('.carStoreSubmit').click(function () {
                $.kish.EditCarStore.EditCarStore();
            });
        },
        SetProvDrp: function () {
            var provinceDrp = $('.provinceDrp');
            var url = '../../KishCar/Services/CarAnn.svc/GetAllProvince';
            var data = '';
            var topOption = 'انتخاب کنید';
            $.Jahanutility.fillDrp(provinceDrp, url, data, topOption);
        },
        GetCarStoreInfo: function () {
            $.ajax({
                url: '../../KishCar/Services/CarAnn.svc/GetCarStore',
                data: JSON.stringify({ carStoreID: $.kish.EditCarStore.carStoreID }),
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data['d'] != null) {
                        $('.NameTxt').val(data['d'].Name);
                        $('.ManagerTxt').val(data['d'].ManagerName);
                        $('.provinceDrp').val(data['d'].Province.ID);
                        $('.TelTxt').val(data['d'].Telephone);
                        $('.emailTxt').val(data['d'].Email);
                        $('.AddressTxt').val(data['d'].Address);
                        $('.commentTxt').val(data['d'].Description);
                        $(".keyWordTxt1").val(data['d'].KeyWords.split(",")[0]);
                        $(".keyWordTxt2").val(data['d'].KeyWords.split(",")[1]);
                        $(".keyWordTxt3").val(data['d'].KeyWords.split(",")[2]);
                        $(".keyWordTxt4").val(data['d'].KeyWords.split(",")[3]);
                        $(".keyWordTxt5").val(data['d'].KeyWords.split(",")[4]);
                    }
                },
                error: function () {
                }
            });
        },
        //*************************//
        ListCarInCarStore: function (start, end, withtotal) {
            $.ajax({
                url: '../../KishCar/Services/CarAnn.svc/GetCarOfCarStore',
                data: JSON.stringify({ carStoreID: $.kish.EditCarStore.carStoreID, Start: start, End: end, WithTotal: withtotal }),
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {

                    if (data['d'] != null) {
                        if (data['d'].length == 0) {
                            $.kish.message.getErrorMessage("15");
                        }
                        else {
                            $('.carOfCarStoreTable').html('');
                            var tableHeader = '<tr><th >تصویر</th><th>برند</th><th>مدل</th><th>رنگ</th><th>سال تولید</th><th>کارکرد</th><th>وضعیت</th><th>ویرایش</th><th>حذف</th></tr>';
                            $('.carOfCarStoreTable').append(tableHeader);
                            for (var i = 0; i < data['d'].Data.length; i++) {
                                var path = '';
                                if (data['d'].Data[i].CarImages[0] != null && data['d'].Data[i].CarImages[0].Path != null) {
                                    path = (data['d'].Data[i].CarImages[0].Path);
                                    var relatedPath = '../' + path.replace('~', '..');
                                    var Image = '<a  class="highslide" href="' + relatedPath + '"> <img  class="width80 fn_prodImg " alt="' + data['d'].Data[i].Name + '" title="تصویر بزرگتر" src= "' + relatedPath + '"/></a>';
                                }
                                var Satus = data['d'].Data[i].IsActive ? "تایید شده" : "تایید نشده"
                                var x = '<tr id=' + data['d'].Data[i].ID + '><td >' + (path ? Image : "بدون تصویر") + ' </td><td class=" breakWord">' + $.trim(data['d'].Data[i].Model.Brand.Code) + ' </td ><td>' + $.trim(data['d'].Data[i].Model.Code) + '</td><td>' + $.trim(data['d'].Data[i].Color.Code) + '</td><td>' + $.trim(data['d'].Data[i].ProductYear) + '</td><td>' + $.trim(data['d'].Data[i].TraveledDistance) + '</td><td>' + Satus + '</td>' +
                                '<td><img alt="ویرایش" title="ویرایش" class="noBorder  inline-block pointer fn_CarinCarStoreEdit" src="../../Images/ico/edit.gif" /></td><td><img alt="ویرایش" title="ویرایش" class="noBorder  inline-block pointer fn_CarInCarStoreDel" src="../../Images/ico/delete.gif" /></td></tr>';
                                $('.carOfCarStoreTable').append(x);
                                $('.carOfCarStoreTable tr:last').data('DTO', data['d'].Data[i])
                            };

                            $('.fn_CarinCarStoreEdit').click(function () {
                                var carID = $(this).closest("tr").attr('id');
                                window.location.replace("./CarAddEdit.aspx?carStoreID=" + $.kish.EditCarStore.carStoreID + "&carID=" + carID);
                            });

                            $('.fn_CarInCarStoreDel').click(function () {
                                var carID = $(this).closest("tr").attr('id');
                                $.kish.EditCarStore.DeleteCarFromCarStore(carID, $(this).closest("tr"))
                            });

                            $('a.highslide').click(function () {
                                return hs.expand(this)
                            });

                            if (withtotal && data['d'].TotalCount && data['d'].TotalCount > 0 && data['d'].TotalCount != null) {
                                $.kish.EditCarStore.WithTotal = data['d'].TotalCount;
                                $.kish.EditCarStore.SetPaging();
                            }
                        }
                    }
                }
            });
        },

        SetPaging: function () {
            var withTotal = $.kish.EditCarStore.WithTotal;
            var PageCount = Math.ceil(withTotal / 20);
            var paging = '';
            for (var i = 0; i < PageCount; i++) {
                var PageItem = '<span class="pagingItem">' + (i + 1).toString() + '</span>';
                paging = paging + PageItem;
            }
            $('.PagingDiv').text('');
            $('.PagingDiv').append(paging);
            $('.PagingDiv').append('<span class="totalCount"> کل موارد یافت شده : ' + withTotal + '</span>');
            $('.pagingItem', '.PagingDiv').click(function () {
                var pageIndex = $(this).text();
                $.kish.EditCarStore.ListCarInCarStore((pageIndex - 1) * 20, pageIndex * 20, false);
            });
        },
        EditCarStore: function () {

            //start--------this part belongs to validation code  "focusout" helps to find empty inputs----------//
            // Kick in Validation
            $('.drpValidator').each(function () {
                $(this).triggerHandler("focusout");
            });

            $('.isNumeric').each(function () {
                $(this).triggerHandler("focusout");
            });

            if ($('#contact .error').size() > 0) {
                $('#contact').effect('shake', { times: 3 }, 50);
                return false;
            }
            //end--------this part belongs to validation code  "focusout" helps to find empty inputs-----------//


            var carStore = {};
            if ($.kish.EditCarStore.carStoreID != '') {
                carStore.ID = $.kish.EditCarStore.carStoreID;
            }
            else {
                carStore.ID = 0;
            }
            carStore.Name = $('.NameTxt').val();
            carStore.ManagerName = $('.ManagerTxt').val();
            if ($(".provinceDrp").val() != 0) {
                carStore.ProvinceID = parseInt($(".provinceDrp").val(), 10);
            }
            else {
                carStore.ProvinceID = null;
            }
            carStore.CarStoreTariffID = 1;
            carStore.Telephone = $('.TelTxt').val();
            carStore.Email = $('.emailTxt').val();
            carStore.Address = $('.AddressTxt').val();
            carStore.Description = $('.commentTxt').val();
            carStore.KeyWords = '';
            carStore.KeyWords += ',' + $(".keyWordTxt1").val();
            carStore.KeyWords += ',' + $(".keyWordTxt2").val();
            carStore.KeyWords += ',' + $(".keyWordTxt3").val();
            carStore.KeyWords += ',' + $(".keyWordTxt4").val();
            carStore.KeyWords += ',' + $(".keyWordTxt5").val();


            $.ajax({
                'type': 'POST',
                'url': '../../KishCar/Services/CarAnn.svc/UpdateCarStore',
                'data': JSON.stringify({ CarStore: carStore }),
                'contentType': 'application/json; charset=utf-8',
                'dataType': 'json',
                'async': false,
                'success': function (result) {
                    if (result['d'].IsSucceed) {
                        $.kish.message.showUserMessage(result['d'].Message.Message);
                        //  window.location.href = 'CarStoresOfUser.aspx';
                    }
                    else {
                        $.kish.message.showErrorMessage(result['d'].Message.Message);
                    };
                    $('#message').slideDown();
                    $('img.loader').fadeOut('slow', function () { $(this).remove() });
                    $('#submit').removeAttr('disabled', 'disabled');
                },
                'error': function (error) {
                    $('#submit').removeAttr('disabled');
                    $('img.loader').fadeOut('slow', function () { $(this).remove() });
                }
            });
        },
        DeleteCarFromCarStore: function (carID, row) {
            $.ajax({
                'type': 'POST',
                'url': '../../KishCar/Services/CarAnn.svc/DeleteCarInCarStore',
                'data': JSON.stringify({ CarStoreID: $.kish.EditCarStore.carStoreID, CarID: carID }),
                'contentType': 'application/json; charset=utf-8',
                'dataType': 'json',
                'async': false,
                'success': function (result) {
                    if (result['d'].IsSucceed) {
                        $.kish.message.showUserMessage(result['d'].Message.Message);
                        row.remove();
                    }
                    else {
                        $.kish.message.showErrorMessage(result['d'].Message.Message);
                    };
                    $('#message').slideDown();
                    $('img.loader').fadeOut('slow', function () { $(this).remove() });
                    $('#submit').removeAttr('disabled', 'disabled');
                },
                'error': function (error) {
                    $('#submit').removeAttr('disabled');
                    $('img.loader').fadeOut('slow', function () { $(this).remove() });
                }
            });
        }
    });
    $.kish.EditCarStore.initializing();
});